import ij.IJ;
import ij.ImagePlus;
import ij.ImageStack;
import ij.gui.GenericDialog;
import ij.gui.NewImage;
import ij.plugin.filter.PlugInFilter;
import ij.process.ImageProcessor;

import java.awt.Point;
import java.util.List;

public class Trajectory_ShowAsStack implements PlugInFilter {
	
	static int boxRadius = 2;
	ImagePlus origImage = null;
	
	public int setup(String arg, ImagePlus img) { 
    	origImage = img;
		return DOES_RGB;
	}
	
	@SuppressWarnings("unchecked")
	public void run(ImageProcessor ip) {
		String PROPKEY = TrajectoryUtils.PROPKEY;	// the key to this property
		List<Point[]> trajList = (List<Point[]>) origImage.getProperty(PROPKEY);
		if (trajList == null) {
			IJ.error("No trajectories found!");
			return;
		}
		
		if (!getParameters()) {
			return;
		}
		
		int[][][] trajArray = TrajectoryUtils.makeTrajectoryArray(trajList);
		if (trajArray == null) {
			IJ.error("Some trajectories are too short (<3)!");
			return;
		}
		
		ImagePlus simg = makeStackImage(trajArray);
		simg.show();
	}
	
	boolean getParameters() {
		GenericDialog gd = new GenericDialog("Trajectories to Stack");
		gd.addNumericField("box radius", boxRadius, 0);
		gd.showDialog();
		if (gd.wasCanceled()) {
			return false;
		}
		boxRadius = (int) gd.getNextNumber();
		return true;
	}
	
	ImagePlus makeStackImage (int[][][] trajArray) {
		int w = origImage.getWidth();
		int h = origImage.getHeight();
		int m = trajArray.length; 		// number of points
		int n = trajArray[0].length;	// number of frames
		//ImageStack stack = new ImageStack(w, h);
		ImagePlus stackimg = 
			NewImage.createByteImage("Title", w, h, n, NewImage.FILL_WHITE);
		ImageStack stack = stackimg.getStack();
		for (int k=0; k<n; k++) {		// frame k
			ImageProcessor frame = stack.getProcessor(k+1);
			frame.setColor(0);		// draw black
			for (int i=0; i<m; i++) {		// trajectory i
				int xi = trajArray[i][k][0];
				int yi = trajArray[i][k][1];
				Point p = new Point(xi,yi);
				TrajectoryUtils.drawSquare(p, frame, boxRadius);
			}
		}
		return stackimg;
	}
	

}
	
